import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken, getUserid, setUserid, removeUserid } from "@/utils/auth";
import router, { resetRouter } from "@/router";

import store from "@/store";

const state = {
  token: getToken(),

  userid: getUserid(),

  is_admin: null,
  name: "",
  avatar: "",
  roles: [],
  code: '',
  venuelist: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERID: (state, userid) => {
    state.userid = userid;
  },
  SET_ISADMIN: (state, is_admin) => {
    state.is_admin = is_admin;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_CODE: (state, code) => {
    state.code = code;
  },

  SET_VENUELIST: (state, venuelist) => {
    state.venuelist = venuelist;
  }
};

const actions = {
	setCode({ commit }, code){
    commit("SET_CODE", code);
	},


  // user login
  login({ commit }, userInfo) {
    // const { username, password, merchant_code } = userInfo;
    const { username, password, merchant_code } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response;
          console.log(data,'login')
          // commit("SET_TOKEN", data.access_token);
          // setToken(data.access_token);
          commit("SET_TOKEN", data.token);
          commit("SET_USERID", data.userid);
          setToken(data.token);
          setUserid(data.userid);

          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit("SET_NAME", '超级管理员');
      commit("SET_ISADMIN", 1);
      const data = {
        real_name: '超级管理员',
        is_admin : 1
      }
      resolve(data);
      // getInfo(state.token)
      //   .then(response => {
      //     const { data } = response;

      //     if (!data) {
      //       return reject("Verification failed, please Login again.");
      //     }

      //     // const { real_name, avatar, role, is_admin } = data.user_info;
      //     // commit("SET_ROLES", role);
      //     // commit("SET_NAME", real_name);
      //     // commit("SET_ISADMIN", is_admin);
      //     // commit("SET_VENUELIST", data.gym_list)
      //     resolve(data);
      //   })
      //   .catch(error => {
      //     reject(error);
      //   });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   sessionStorage.clear()
      //   commit('SET_ROLES', [])
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      // console.log("-1-1", window.location.href)
      // return
      if(typeof logoutJumpUrl !="undefined" && logoutJumpUrl)
      {
        window.location.href = logoutJumpUrl
      }
      removeToken(); // must remove  token  first
      removeUserid()
      resetRouter();
      sessionStorage.clear();
      commit("SET_ROLES", []);
      commit("SET_NAME", '');
      // store.commit('permission/SET_ROUTES', [])
      // store.dispatch(
      //   "permission/setRoute", []
      // )
      // commit("SET_ROUTES", []);
      // commit("SET_TOKEN", '');
      // SET_ROUTES
      // console
      // console.log("hasroutes11111",store.getters.permission_routes)
      // window.location.reload();
      // console.log("hasroutes2",store.getters.permission_routes)
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("SET_ROLES", []);
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    // dispatch('tagsView/delAllViews', null, { root: true })
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
